package cn.jhc.teachingquality.fragment;

import android.content.SharedPreferences;
import android.graphics.Rect;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jhc.teachingquality.Global;
import cn.jhc.teachingquality.R;
import cn.jhc.teachingquality.adapter.StudentAdapter;
import cn.jhc.teachingquality.bean.Student;
import cn.jhc.teachingquality.bean.TeachingLog;
import cn.jhc.teachingquality.loader.StudentsAsyncLoader;
import cn.jhc.teachingquality.net.RequestQueueFactory;
import cn.jhc.teachingquality.net.teaching.SaveTeachingLogRequest;

/**
 * Created by luyanfei on 16-4-18.
 */
public class TeachingLogFragment extends Fragment
        implements LoaderManager.LoaderCallbacks<List<Student>>, View.OnClickListener{

    private Button saveButton;
    private EditText contentEditText;
    private TeachingLog teachingLog;
    private RecyclerView checkRollView;
    private List<Student> studentList;
    private SharedPreferences sharedPreferences;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_teaching_log, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Bundle args = getArguments();
        teachingLog = (TeachingLog)args.getSerializable(Global.CURRENT_TEACHING_LOG);
        TextView mainTitleView = (TextView)getView().findViewById(R.id.teaching_log_main_title);
        mainTitleView.setText(teachingLog.getMainTitle());
        TextView subTitleView = (TextView)getView().findViewById(R.id.teaching_log_sub_title);
        subTitleView.setText(teachingLog.getSubTitle());

        contentEditText = (EditText)getView().findViewById(R.id.edit_lesson_content);

        //save button should disabled before fetch student names.
        saveButton = (Button) getView().findViewById(R.id.btn_save_lesson_content);
        saveButton.setClickable(false);

        checkRollView = (RecyclerView)getView().findViewById(R.id.checkroll_view);

        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());

        getLoaderManager().initLoader(0, null, this).forceLoad();
    }

    @Override
    public Loader<List<Student>> onCreateLoader(int id, Bundle args) {
        return new StudentsAsyncLoader(getActivity(), teachingLog);
    }

    @Override
    public void onLoadFinished(Loader<List<Student>> loader, List<Student> data) {
        this.studentList = data;
        StudentAdapter studentAdapter = new StudentAdapter(getActivity(), data);
        checkRollView.setAdapter(studentAdapter);
        checkRollView.setLayoutManager(new GridLayoutManager(getActivity(), 4));
        checkRollView.addItemDecoration(new StudentItemDecoration(10, 4));
        saveButton.setClickable(true);
        saveButton.setOnClickListener(this);
    }

    @Override
    public void onLoaderReset(Loader<List<Student>> loader) {

    }
    //保存教学日志
    @Override
    public void onClick(View v) {
        saveButton.setClickable(false);
        Map<String,Object> formData = new HashMap<>();
        String lessonContent = contentEditText.getText().toString();
        formData.put("content_of_lesson", lessonContent);
        formData.put("teaching_log_object", teachingLog);
        formData.put("students_list", studentList);
        SaveTeachingLogRequest saveRequest = new SaveTeachingLogRequest(formData, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Toast.makeText(getContext(),"教学日志保存成功。",Toast.LENGTH_SHORT).show();
                //退回MainFragment
                getActivity().onBackPressed();
            }
        });
        RequestQueueFactory.getRequestQueue(getContext()).add(saveRequest);
    }

    private static class StudentItemDecoration extends RecyclerView.ItemDecoration{
        private int spacing;
        private int spanCount;
        public StudentItemDecoration(int spacing, int spanCount){
            this.spacing = spacing;
            this.spanCount = spanCount;
        }
        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            int position = parent.getChildAdapterPosition(view); // item position
            int column = position % spanCount; // item column
            outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
            outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)

            if (position < spanCount) { // top edge
                outRect.top = spacing;
            }
            outRect.bottom = spacing; // item bottom
        }
    }
}
